﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using StartupTaskRunner.Logging;
using System.Diagnostics.Contracts;
using System.Security.Cryptography.X509Certificates;

namespace StartupTaskRunner.Actions
{
    public class InstallCertificateAction : ActionBase
    {
        public override string Type
        {
            get { return "InstallCertificate"; }
        }        
        
        public override void Execute()
        {
            Logger.WriteMessage("Installing certificate {0} in certificate store {1} for {2}", CertificateFile, CertStoreName, CertStoreLocation);

            StoreLocation storeLocation;

            // Convert Location to StoreLocation
            switch(CertStoreLocation.ToLower())
            {
               case "localmachine":
                    storeLocation = StoreLocation.LocalMachine;
                    break;
              default:
                    storeLocation = StoreLocation.CurrentUser;
                    break;
            }

            // Read file as X.509
            X509Certificate2 cert = new X509Certificate2(CertificateFile);

            // Create store, open and add the certificate
            X509Store store = new X509Store(CertStoreName, storeLocation);
            try
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(cert);
                Logger.WriteMessage("Installed certificate {0} in certificate store {1} for {2}", CertificateFile, CertStoreName, CertStoreLocation);
            }
            catch (Exception e)
            {
                Logger.WriteMessage("Failed to install certificate {0} in store {1} for {2}", CertificateFile, CertStoreName, CertStoreLocation);
                Logger.LogException(e);
            }
            finally 
            {
                store.Close();
            }
        }

        public string CertificateFile { get; set; }
        public string CertStoreName { get; set; }
        public string CertStoreLocation { get; set; }
    }
}
